/************************************************************
 *  * Hyphenate CONFIDENTIAL
 * __________________
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of Hyphenate Inc.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Hyphenate Inc.
 */

#import "ConversationListController.h"
#import "MBTPre.h"
#import "ChatViewController.h"
#import "EMSearchBar.h"
//#import "EMSearchDisplayController.h"
//#import "RobotManager.h"
//#import "RobotChatViewController.h"
//#import "UserProfileManager.h"
#import "RealtimeSearchUtil.h"
//#import "RedPacketChatViewController.h"
//#import "ChatDemoHelper.h"
#import "TCallKeyborad.h"
#import "ChatDemoHelper.h"
#import "CallToWatchStateVC.h"
#import "AddBlacklist.h"
#import "AddMark.h"
#import "CustomizeView.h"
#import "HttpTool.h"
#import "BindTool.h"
#import "MarkInfo.h"
#import "LewPopupViewController.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "DbManage.h"
#import "RunSucessInfo.h"
#import "DataTool.h"
#import "TContact.h"
@implementation EMConversation (search)

//根据用户昵称,环信机器人名称,群名称进行搜索
//- (NSString*)showName
//{
//    if (self.type == EMConversationTypeChat) {
////        if ([[RobotManager sharedInstance] isRobotWithUsername:self.conversationId]) {
////            return [[RobotManager sharedInstance] getRobotNickWithUsername:self.conversationId];
////        }
//        return [[UserProfileManager sharedInstance] getNickNameWithUsername:self.conversationId];
//    } else if (self.type == EMConversationTypeGroupChat) {
//        if ([self.ext objectForKey:@"subject"] || [self.ext objectForKey:@"isPublic"]) {
//            return [self.ext objectForKey:@"subject"];
//        }
//    }
//    return self.conversationId;
//}

@end

@interface ConversationListController ()<EaseConversationListViewControllerDelegate, EaseConversationListViewControllerDataSource,UISearchDisplayDelegate, UISearchBarDelegate,TCallKeyboradDelegate,UIGestureRecognizerDelegate,ABNewPersonViewControllerDelegate,AddBlacklistelegate>
{
    BOOL isOnlyShow;
    BOOL isTagShow;
    BOOL isShowCustom;
    MarkInfo *markInfo;
    NSString *user_id;
}


@property (nonatomic, strong) UIView *networkStateView;
@property (nonatomic, strong) EMSearchBar           *searchBar;

//@property (strong, nonatomic) EMSearchDisplayController *searchController;
@property (nonatomic, strong) TCallKeyborad           *keyboard;
@property (nonatomic ,strong)UISearchController *searchVC;
//@property (nonatomic,strong) AddBlacklist *h;
@end

@implementation ConversationListController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"ConversationListController");
    // Do any additional setup after loading the view.
    self.showRefreshHeader = YES;
    self.delegate = self;
    self.dataSource = self;
    
    [self tableViewDidTriggerHeaderRefresh];
    
    [self.view addSubview:self.searchBar];
    self.tableView.frame = CGRectMake(0, self.searchBar.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - self.searchBar.frame.size.height);
    [self networkStateView];
    
    //[self searchController];
    
    [self removeEmptyConversationsFromDB];
    _keyboard = [TCallKeyborad headerView];
    _keyboard.hidden=YES;
    _keyboard.delegate=self;
     _keyboard.frame =CGRectMake(0, SCREEN_H-_keyboard.frame.size.height-120, SCREEN_W, _keyboard.frame.size.height);
    [self.view addSubview:_keyboard];
    [self longPressClick];
    user_id =[BindTool share].bindInfo.phone_number;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self refresh];
    //[self removeEmptyConversationsFromDB];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)removeEmptyConversationsFromDB
{
    NSLog(@"removeEmptyConversationsFromDB");
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (!conversation.latestMessage || (conversation.type == EMConversationTypeChatRoom)) {
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            
            [needRemoveConversations addObject:conversation];
        }
    }
    
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EMClient sharedClient].chatManager deleteConversations:needRemoveConversations isDeleteMessages:YES completion:nil];
    }
}

#pragma mark - getter
- (UIView *)networkStateView
{
    if (_networkStateView == nil) {
        _networkStateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 44)];
        _networkStateView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:199 / 255.0 blue:199 / 255.0 alpha:0.5];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (_networkStateView.frame.size.height - 20) / 2, 20, 20)];
        imageView.image = [UIImage imageNamed:@"messageSendFail"];
        [_networkStateView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + 5, 0, _networkStateView.frame.size.width - (CGRectGetMaxX(imageView.frame) + 15), _networkStateView.frame.size.height)];
        label.font = [UIFont systemFontOfSize:15.0];
        label.textColor = [UIColor grayColor];
        label.backgroundColor = [UIColor clearColor];
        label.text = NSLocalizedString(@"network.disconnection", @"Network disconnection");
        [_networkStateView addSubview:label];
    }
    
    return _networkStateView;
}

- (UISearchBar *)searchBar
{
    if (!_searchBar) {
        NSLog(@"searchBar========");
        _searchBar = [[EMSearchBar alloc] initWithFrame: CGRectMake(0, 0, self.view.frame.size.width, 44)];
        _searchBar.delegate = self;
        _searchBar.placeholder = NSLocalizedString(@"search", @"Search");
        _searchBar.backgroundColor = [UIColor colorWithRed:0.747 green:0.756 blue:0.751 alpha:1.000];
    }
    
    return _searchBar;
}

-(void)addSearchVC
{
    _searchVC = [[UISearchController alloc]initWithSearchResultsController:nil];
    _searchVC.searchResultsUpdater = self;
    _searchVC.dimsBackgroundDuringPresentation = NO;
    _searchVC.hidesNavigationBarDuringPresentation = NO;
    _searchVC.searchBar.frame = CGRectMake(self.searchVC.searchBar.frame.origin.x, self.searchVC.searchBar.frame.origin.y, self.searchVC.searchBar.frame.size.width, 44.0);
    [self.searchVC.searchBar setImage:[UIImage imageNamed:@"搜索"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    self.searchVC.searchBar.delegate =self;
    //[self.view addSubview:self.searchVC.searchBar];
    self.tableView.tableHeaderView = self.searchVC.searchBar;
}



#pragma mark - EaseConversationListViewControllerDelegate

- (void)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
            didSelectConversationModel:(id<IConversationModel>)conversationModel
{
    if (conversationModel) {
        EMConversation *conversation = conversationModel.conversation;
        if (conversation) {
            ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
                chatController.title=conversation.conversationId;
             [self.navigationController pushViewController:chatController animated:YES];
//            if ([[RobotManager sharedInstance] isRobotWithUsername:conversation.conversationId]) {
//                RobotChatViewController *chatController = [[RobotChatViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
//                chatController.title = [[RobotManager sharedInstance] getRobotNickWithUsername:conversation.conversationId];
//                [self.navigationController pushViewController:chatController animated:YES];
//            } else {
//#ifdef REDPACKET_AVALABLE
//                RedPacketChatViewController *chatController = [[RedPacketChatViewController alloc]
//#else
//                ChatViewController *chatController = [[ChatViewController alloc]
//#endif
//                                                      initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
//                chatController.title = conversationModel.title;
//                [self.navigationController pushViewController:chatController animated:YES];
//            }
        }
                                                               
        [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
        [self.tableView reloadData];
    }
}

#pragma mark - EaseConversationListViewControllerDataSource
//这个也是设置的地方
- (id<IConversationModel>)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                                    modelForConversation:(EMConversation *)conversation
{
    EaseConversationModel *model = [[EaseConversationModel alloc] initWithConversation:conversation];
    if (model.conversation.type == EMConversationTypeChat) {
        //model.title = conversation.conversationId;
         model.title =[self setContactName:conversation.conversationId];
//        if ([[RobotManager sharedInstance] isRobotWithUsername:conversation.conversationId]) {
//            model.title = [[RobotManager sharedInstance] getRobotNickWithUsername:conversation.conversationId];
//        } else {
//            UserProfileEntity *profileEntity = [[UserProfileManager sharedInstance] getUserProfileByUsername:conversation.conversationId];
//            if (profileEntity) {
//                model.title = profileEntity.nickname == nil ? profileEntity.username : profileEntity.nickname;
//                model.avatarURLPath = profileEntity.imageUrl;
//            }
//        }
    } else if (model.conversation.type == EMConversationTypeGroupChat) {
        NSString *imageName = @"groupPublicHeader";
        if (![conversation.ext objectForKey:@"subject"])
        {
            NSArray *groupArray = [[EMClient sharedClient].groupManager getJoinedGroups];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:conversation.conversationId]) {
                    NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:conversation.ext];
                    [ext setObject:group.subject forKey:@"subject"];
                    [ext setObject:[NSNumber numberWithBool:group.isPublic] forKey:@"isPublic"];
                    conversation.ext = ext;
                    break;
                }
            }
        }
        NSDictionary *ext = conversation.ext;
        model.title = [ext objectForKey:@"subject"];
        imageName = [[ext objectForKey:@"isPublic"] boolValue] ? @"groupPublicHeader" : @"groupPrivateHeader";
        model.avatarImage = [UIImage imageNamed:imageName];
    }
    return model;
}
//设置的地方
- (NSAttributedString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
      latestMessageTitleForConversationModel:(id<IConversationModel>)conversationModel
{
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:@""];
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];
    if (lastMessage) {
        NSString *latestMessageTitle = @"";
        EMMessageBody *messageBody = lastMessage.body;
        switch (messageBody.type) {
            case EMMessageBodyTypeImage:{
                latestMessageTitle = NSLocalizedString(@"message.image1", @"[image]");
            } break;
            case EMMessageBodyTypeText:{
                // 表情映射。
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                latestMessageTitle = didReceiveText;
                if ([lastMessage.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
                    latestMessageTitle = @"[动画表情]";
                }
            } break;
            case EMMessageBodyTypeVoice:{
                latestMessageTitle = NSLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case EMMessageBodyTypeLocation: {
                latestMessageTitle = NSLocalizedString(@"message.location1", @"[location]");
            } break;
            case EMMessageBodyTypeVideo: {
                latestMessageTitle = NSLocalizedString(@"message.video1", @"[video]");
            } break;
            case EMMessageBodyTypeFile: {
                latestMessageTitle = NSLocalizedString(@"message.file1", @"[file]");
            } break;
            default: {
            } break;
        }
        
        if (lastMessage.direction == EMMessageDirectionReceive) {
            NSString *from = [self setContactName:conversationModel.conversation.conversationId];
//            UserProfileEntity *profileEntity = [[UserProfileManager sharedInstance] getUserProfileByUsername:from];
//            if (profileEntity) {
//                from = profileEntity.nickname == nil ? profileEntity.username : profileEntity.nickname;
//            }
            latestMessageTitle = [NSString stringWithFormat:@"%@: %@", from, latestMessageTitle];
        }
        
        NSDictionary *ext = conversationModel.conversation.ext;
//        if (ext && [ext[kHaveUnreadAtMessage] intValue] == kAtAllMessage) {
//            latestMessageTitle = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"group.atAll", nil), latestMessageTitle];
//            attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
//            [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, NSLocalizedString(@"group.atAll", nil).length)];
//            
//        }
//        else if (ext && [ext[kHaveUnreadAtMessage] intValue] == kAtYouMessage) {
//            latestMessageTitle = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"group.atMe", @"[Somebody @ me]"), latestMessageTitle];
//            attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
//            [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, NSLocalizedString(@"group.atMe", @"[Somebody @ me]").length)];
//        }
//        else {
//            attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
//        }
        attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
    }
    NSLog(@"NSMutableAttributedString===%@",attributedStr);
    return attributedStr;
}

- (NSString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
       latestMessageTimeForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTime = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];;
    if (lastMessage) {
        latestMessageTime = [NSDate formattedTimeFromTimeInterval:lastMessage.timestamp];
    }

    
    return latestMessageTime;
}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    NSLog(@"searchBarShouldBeginEditing");
    [searchBar setShowsCancelButton:YES animated:YES];
    //[[ChatDemoHelper shareHelper].mainVC setKeyBoardHidden:NO];
    _keyboard.hidden=NO;
//    if (!_searchController.active) {
//        _searchController.active=YES;
//    }
    return NO;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"真是无语啊啊啊");
//    if (!_searchController.active) {
//        _searchController.active=YES;
//    }
    __weak typeof(self) weakSelf = self;
    [[RealtimeSearchUtil currentUtil] realtimeSearchWithSource:self.dataArray searchText:(NSString *)searchText collationStringSelector:@selector(title) resultBlock:^(NSArray *results) {
        if (results) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //真正的更新
                NSLog(@"result--====%lu",(unsigned long)results.count);
                [weakSelf.dataArray removeAllObjects];
                if (searchText.length!=0) {//搜索后的结果
                    [weakSelf.dataArray addObjectsFromArray:results];
                }else if(searchText.length==0){
                    [weakSelf.dataArray addObjectsFromArray:weakSelf.unSearchArray];
                    //实现了收缩的功能了啊
                }
                 [weakSelf.tableView reloadData];
//                [weakSelf.searchController.resultsSource removeAllObjects];
//                [weakSelf.searchController.resultsSource addObjectsFromArray:results];
//                [weakSelf.searchController.searchResultsTableView reloadData];
            });
        }
    }];
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
     //[[ChatDemoHelper shareHelper].mainVC setKeyBoardHidden:YES];
    NSLog(@"searchBarShouldEndEditing");
    return YES;
}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    NSLog(@"searchBarSearchButtonClicked");
    return ;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
     NSLog(@"searchBarCancelButtonClicked");
    searchBar.text = @"";
    [[RealtimeSearchUtil currentUtil] realtimeSearchStop];
    [searchBar resignFirstResponder];
    //[[ChatDemoHelper shareHelper].mainVC setKeyBoardHidden:YES];
    _keyboard.hidden=YES;
    [searchBar setShowsCancelButton:NO animated:YES];
}

#pragma mark - public

-(void)refresh
{
    NSLog(@"就是折磨拽啊啊看打卡打卡打卡的");
    [self refreshAndSortView];
}

-(void)refreshDataSource
{
    [self tableViewDidTriggerHeaderRefresh];
}

- (void)isConnect:(BOOL)isConnect{
    if (!isConnect) {
        self.tableView.tableHeaderView = _networkStateView;
    }
    else{
        self.tableView.tableHeaderView = nil;
    }
}

- (void)networkChanged:(EMConnectionState)connectionState
{
    if (connectionState == EMConnectionDisconnected) {
        self.tableView.tableHeaderView = _networkStateView;
    }
    else{
        self.tableView.tableHeaderView = nil;
    }
}
-(void)contactkeyBoard:(UIButton*)b{
    int number = (int)b.tag;
    
    if (number==12) {
        //[[ChatDemoHelper shareHelper].mainVC setKeyBoardHidden:YES];
        _keyboard.hidden=YES;
    }else if(number==13){
        if (_searchBar.text==nil) {
            return;
        }
        CallToWatchStateVC *vc =[[CallToWatchStateVC alloc]init];
        vc.phoneValue=_searchBar.text;
        [self.navigationController pushViewController:vc animated:YES];
    }else if(number==14){
        if (_searchBar.text==nil) {
            return;
        }
        ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:_searchBar.text conversationType:0];
        chatController.title=_searchBar.text;
        [self.navigationController pushViewController:chatController animated:YES];
    }else if(number==15){
        _searchBar.text =nil;
         [self searchBar:_searchBar textDidChange:_searchBar.text];
    }else if(number==10){
        NSString *numbeValue =[NSString stringWithFormat: @"%@",@"*"];
        NSString *text =[_searchBar.text stringByAppendingString:numbeValue];
        _searchBar.text =text;
         [self searchBar:_searchBar textDidChange:text];
    }else if(number==11){
        NSString *numbeValue =[NSString stringWithFormat: @"%@",@"#"];
        NSString *text =[_searchBar.text stringByAppendingString:numbeValue];
        _searchBar.text =text;
         [self searchBar:_searchBar textDidChange:text];
    }else{
        NSString *numbeValue =[NSString stringWithFormat: @"%i",number];
        NSString *text =[_searchBar.text stringByAppendingString:numbeValue];
        _searchBar.text =text;
        [self searchBar:_searchBar textDidChange:text];
    }
}
-(void)longPressClick{
    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    lpgr.minimumPressDuration = 1.0; //seconds  设置响应时间
    lpgr.delegate = self;
    [self.tableView addGestureRecognizer:lpgr];
}
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if(gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        NSLog(@"handleLongPress=======");
    __weak typeof(self) weakSelf = self;
    CGPoint p = [gestureRecognizer locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
    if (indexPath!=nil) {
        //设置代理
        EaseConversationModel *model =[self.dataArray objectAtIndex:indexPath.row];
        if (!isOnlyShow) {
            
            BOOL isHaving;
            NSMutableArray *markArray =[[DbManage shareDbManage]queryMarkArray:model.conversation.conversationId];
            if (markArray.count!=0) {
                //已经存在
                markInfo =[markArray objectAtIndex:0];
                isHaving =YES;
            }else{
                //未存在
                markInfo =[[MarkInfo alloc]init];
                markInfo.number =model.conversation.conversationId;
                isHaving=NO;
            }
            isOnlyShow=YES;
            AddBlacklist *h =[AddBlacklist headerView];
            [self lew_presentPopupView:h animation:[LewPopupViewAnimationDrop new] dismissed:^{
                NSLog(@"挂壁");
                isOnlyShow=NO;
                if (isTagShow){
                    isTagShow=NO;
                    AddMark *mark =[AddMark headerView];
                    [weakSelf lew_presentPopupView:mark animation:[LewPopupViewAnimationFade new] dismissed:^{
                        NSLog(@"这是什么啊啊");
                    }];
                    mark.closeblock = ^(){
                        NSLog(@"走没有走dshdh");
                        //在这里另外找个对话框
                         [weakSelf lew_dismissPopupView];
                    };
                    mark.cancleTagBlock = ^(){
                        NSLog(@"cancleblock取消标记");
                        [weakSelf lew_dismissPopupView];
                        if (isHaving) {
                            [weakSelf delteMarkToServer:markInfo];
                        }
                    };
                    mark.cancleblock = ^(){
                        [weakSelf lew_dismissPopupView];
                    };
                    mark.okTagBlock=^(NSString *showText){
                        [weakSelf lew_dismissPopupView];
                        NSLog(@"showText======%@",showText);
                        //添加或者修改标记
                        markInfo.mark =showText;
                        if (isHaving) {
                            [weakSelf updateMarkToServer:markInfo];
                        }else{
                            markInfo.time= [DataTool getStringTimestamp:[NSDate date]];
                            [weakSelf addMarkToServer:markInfo];
                        }
                    };
                }
            }];
            h.tagBlock =^{
                [weakSelf lew_dismissPopupView];
                isTagShow=YES;
            };
            h.contactBlock =^{
                NSLog(@"加为联系人");
                [weakSelf lew_dismissPopupView];
                ABNewPersonViewController *p =[[ABNewPersonViewController alloc]init];
                p.newPersonViewDelegate =weakSelf;
                [weakSelf.navigationController pushViewController:p animated:YES];
            };
        }
    }
}
}
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(nullable ABRecordRef)person;{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)addMarkToServer:(MarkInfo *)info{
    //添加标记
    NSDictionary *pa =@{@"user_id":user_id,@"number":info.number,@"mark":info.mark,@"time":info.time,@"data":@""};
    NSString *url =[apiUrl stringByAppendingString:addMark];
    [HttpTool Post:url parameters:pa success:^(id responseObject) {
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"addMarkToServer====%@",str);
        RunSucessInfo *success =[RunSucessInfo mj_objectWithKeyValues:responseObject];
        if (success.status) {
            //插入数据库中
            NSMutableArray *array =[NSMutableArray array];
            [array addObject:info];
            [[DbManage  shareDbManage] insertMarkInfoArray:array];
        }
    } failure:^(NSError *error){
        
    }];
}
-(void)updateMarkToServer:(MarkInfo *)info{
    NSDictionary *pa =@{@"user_id":user_id,@"number":info.number,@"mark":info.mark,@"time":info.time,@"data":@""};
    NSString *url =[apiUrl stringByAppendingString:saveMark];
    [HttpTool Post:url parameters:pa success:^(id responseObject) {
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"updateMarkToServer====%@",str);
        RunSucessInfo *success =[RunSucessInfo mj_objectWithKeyValues:responseObject];
        if (success.status) {
            //插入数据库中
            NSMutableArray *array =[NSMutableArray array];
            [array addObject:info];
            [[DbManage  shareDbManage] updateMarkInfo:array];
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)delteMarkToServer:(MarkInfo *)info{
    NSString *url =[apiUrl stringByAppendingString:deleteMark];
    NSDictionary *pa =@{@"user_id":user_id,@"number":info.number};
    [HttpTool GET:url WithHeader:NO parameters:pa success:^(id responseObject) {
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"delteMarkToServer====%@",str);
         RunSucessInfo *success =[RunSucessInfo mj_objectWithKeyValues:responseObject];
        if (success.status) {
            //插入数据库中
            NSMutableArray *array =[NSMutableArray array];
            [array addObject:info];
            [[DbManage  shareDbManage] deleteMarkArray:array];
            //删除，然后开始进来的时候去获取所有的mark,同步到服务器中去
        }
    } failure:^(NSError *error) {
        
    }];
}
-(NSString *)setContactName:(NSString *)phone{
    NSMutableArray *array =[[DbManage shareDbManage] queryConatctArray:phone];
    if (array.count!=0) {
        TContact *conatct =[array objectAtIndex:0];
        return conatct.name;
    }else{
        return phone;
    }
}
@end
